package com.hirsi.module.developer.service;

import com.hirsi.common.core.enums.DeveloperStatusEnum;
import com.hirsi.common.core.exception.ServerRuntimeException;
import com.hirsi.common.core.util.AccessTokenUtil;
import com.hirsi.common.db.developer.entity.Developer;
import com.hirsi.common.db.developer.entity.DeveloperApply;
import com.hirsi.common.db.developer.entity.DeveloperAudit;
import com.hirsi.common.db.developer.service.IDeveloperApplyService;
import com.hirsi.common.db.developer.service.IDeveloperAuditService;
import com.hirsi.common.db.developer.service.IDeveloperService;
import com.hirsi.module.developer.vo.param.AuditDeveloperParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DeveloperService {

    @Autowired
    private IDeveloperService iDeveloperService;

    @Autowired
    private IDeveloperApplyService iDeveloperApplyService;

    @Transactional(rollbackFor = Exception.class)
    public void auditApply(AuditDeveloperParam param) {
        Developer developer = iDeveloperService.lambdaQuery()
                .eq(Developer::getId, param.getId())
                .select(Developer::getStatus).last("limit 1").one();
        if (developer == null) throw new ServerRuntimeException("开发者不存在");
        else if (!DeveloperStatusEnum.AUDIT.getValue().equals(developer.getStatus())
                && !DeveloperStatusEnum.REJECT.getValue().equals(developer.getStatus())) {
            throw new ServerRuntimeException("此开发者已经审核过");
        }
        iDeveloperService.lambdaUpdate()
                .eq(Developer::getId, param.getId())
                .set(Developer::getStatus, param.getStatus()).update();
        DeveloperApply developerApply = iDeveloperApplyService.lambdaQuery()
                .eq(DeveloperApply::getDeveloperId, param.getId())
                .orderByDesc(DeveloperApply::getCreateTime)
                .last("limit 1")
                .select(DeveloperApply::getId).one();
        //添加一条审核记录
        new DeveloperAudit().setDeveloperId(param.getId())
                .setApplyId(developerApply.getId())
                .setReply(param.getReply())
                .setCreateUser(AccessTokenUtil.getUserId())
                .setStatus(param.getStatus()).insert();
    }
}
